package com.learn.project.leetcode.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 不同的二叉搜索树二
 * 给你一个整数 n ，请你生成并返回所有由 n 个节点组成且节点值从 1 到 n 互不相同的不同 二叉搜索树 。可以按 任意顺序 返回答案
 * @author chenfuyuan
 * @date 2022/3/15 9:10
 */
public class UniqueBinarySearchTreesTwo {

    public static void main(String[] args) {
        UniqueBinarySearchTreesTwo uniqueBinarySearchTreesTwo = new UniqueBinarySearchTreesTwo();
        List<TreeNode> treeNodes = uniqueBinarySearchTreesTwo.generateTrees(3);
        for (TreeNode treeNode : treeNodes) {
            List<Integer> printList = TreeUtil.print(treeNode);
            System.out.println(printList);

        }
    }

    public List<TreeNode> generateTrees(int n) {
        if (n == 0) {
            return new ArrayList<>();
        }

        return generateTrees(1, n);
    }

    private List<TreeNode> generateTrees(int start, int end) {
        List<TreeNode> allTree = new LinkedList<>();

        //终止条件
        if (start > end) {
            allTree.add(null);
            return allTree;
        }

        for (int i = start; i <= end; i++) {
            //获取符合要求的左子树
            List<TreeNode> leftTreeList = generateTrees(start,i-1);
            //获取符合要求的右子树
            List<TreeNode> rightTreeList = generateTrees(i+1, end);

            System.out.print("");
            for (TreeNode leftTree : leftTreeList) {
                for (TreeNode rightTree : rightTreeList) {
                    TreeNode tree = new TreeNode(i);
                    tree.left = leftTree;
                    tree.right = rightTree;
                    allTree.add(tree);
                }
            }
        }

        return allTree;
    }
}
